package org.example.fancystudy.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author chaigq
 * @version 1.0
 * @date 2023/2/17 15:17
 */
public class SpinLockDemo {
    AtomicReference<Thread> SpinLock = new AtomicReference<>();
    public void Lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "---准备加锁---");
        while (!SpinLock.compareAndSet(null, thread)){

        }
        System.out.println(thread.getName() + "---加锁成功---");
    }

    public void unLock(){
        Thread thread = Thread.currentThread();
        SpinLock.compareAndSet(thread, null);
        System.out.println(thread.getName() + "---解锁成功---");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.Lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            spinLockDemo.unLock();
        },"A").start();

        try {
            TimeUnit.MILLISECONDS.sleep(500);
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        new Thread(() -> {
            spinLockDemo.Lock();
            spinLockDemo.unLock();
        }, "B").start();
    }
}
